<template>
  <div>
    <UploadExcel :on-success="handleSuccess" />
  </div>
</template>

<script>
import { barchAddEmpAPI } from '@/api/employees'
export default {
  name: 'uploadExcel',
  methods: {
    /**
     * 批量上传数据
     */
    async handleSuccess ({ results }) {
      console.log('results:', results)
      const data = this.dataFormatter(results)
      await barchAddEmpAPI(data)
      // 数据处理
      console.log(data)
      this.$message.success('添加成功')
      this.$router.back()
    },

    /**
     * 格式化数据
     */
    dataFormatter (results) {
      const userRelations = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber'
      }
      const result = []
      results.forEach(item => {
        const obj = {}
        Object.keys(item).forEach(item2 => {
          const englishKey = userRelations[item2]
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            obj[englishKey] = this.formatExcelDate(item[item2], '-')
          } else {
            obj[englishKey] = item[item2]
          }
        })
        result.push(obj)
      })
      return result
    },
    /**
     * 转换excel的日期格式
     */
    formatExcelDate (numb, format) {
      const time = new Date(numb * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return (
          year +
          format +
          (month < 10 ? '0' + month : month) +
          format +
          (date < 10 ? '0' + date : date)
        )
      }
      return (
        year +
        '-' +
        (month < 10 ? '0' + month : month) +
        '-' +
        (date < 10 ? '0' + date : date)
      )
    }
  }
}
</script>

<style></style>
